"""
Python SMTP发送邮件
"""

import smtplib
from smtplib import SMTP_SSL
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.header import Header

import random
from .configreader import Reader

my_sender = Reader.getConfig('smtp', 'host_server')
my_qq = Reader.getConfig('smtp', 'sender_qq')
my_pwd = Reader.getConfig('smtp', 'pwd')
mail_title = Reader.getConfig('smtp', 'mail_title') #邮件标题


class MailSender(object):
    def GenerateRandomCode(self)->str:
        rand_list =  random.sample('0123456789',6)
        code = ""
        for ch in rand_list:
            code+= ch
        return code

    # 发送邮件的服务
    @classmethod
    def SendCheckCode(self,receiver_mail)->bool:
        check_code = self.GenerateRandomCode(self)
        #邮件正文内容
        mail_content = "您好，<p>这是"+mail_title+"给你发送的邮箱:{}</p>".format(check_code)

        msg = MIMEMultipart()
        msg["Subject"] = Header(mail_title,'utf-8')
        msg["From"] = my_qq
        msg["To"] = Header(mail_title,"utf-8")

        msg.attach(MIMEText(mail_content,'html'))
        try:
            smtp = SMTP_SSL(my_sender) # ssl登录连接到邮件服务器
            smtp.set_debuglevel(1) # 0是关闭，1是开启debug
            smtp.ehlo(my_sender) # 跟服务器打招呼，告诉它我们准备连接，最好加上这行代码
            smtp.login(my_qq,my_pwd)
            smtp.sendmail(my_qq,receiver_mail,msg.as_string())
            smtp.quit()
            print("邮件发送成功")
            return [check_code,True]
        except smtplib.SMTPException:
            print("无法发送邮件")
            return [None,False]


    @classmethod
    def SendPwd(self,receiver_mail,pwd)->bool:
        mail_content = "您好，<p>这是"+mail_title+"。账号{}所对应的密码为{}</p>".format(receiver_mail,pwd)
        msg = MIMEMultipart()
        msg["Subject"] = Header(mail_title,'utf-8')
        msg["From"] = my_qq
        msg["To"] = Header(mail_title,"utf-8")

        msg.attach(MIMEText(mail_content,'html'))
        try:
            smtp = SMTP_SSL(my_sender) # ssl登录连接到邮件服务器
            smtp.set_debuglevel(1) # 0是关闭，1是开启debug
            smtp.ehlo(my_sender) # 跟服务器打招呼，告诉它我们准备连接，最好加上这行代码
            smtp.login(my_qq,my_pwd)
            smtp.sendmail(my_qq,receiver_mail,msg.as_string())
            smtp.quit()
            print("邮件发送成功")
            return True
        except smtplib.SMTPException:
            print("无法发送邮件")
            return False

if __name__ == '__main__':
    MailSender.SendCheckCode('1402881940@qq.com')

